package main

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"os/exec"

	"github.com/fsnotify/fsnotify"
)

/*****************
 * 监控配置压缩包，发生变动就刷新到peer或orderer的配置目录
 * 执行：./main name_space org_name|orderer peer{index}|index（如：./main bchr9haipn5k org1 peer0, ./main bchr9haipn5k orderer 0）
 ****************/

func main() {
	log.Printf("refresh config task start...\n")
	refresh()
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				log.Println("event:", event)
				if event.Op&fsnotify.Write == fsnotify.Write {
					log.Println("modified file:", event.Name)
				}
				refresh()
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	if os.Args[1] == "bcos" {
		err = watcher.Add("/opt/config/bcos-config/node0_base64")
		if err != nil {
			log.Fatal(err)
		}
	} else if os.Args[1] == "chainmaker" {
		err = watcher.Add("/opt/config/" + os.Args[2] + "_base64")
		if err != nil {
			log.Fatal(err)
		}
	} else {
		if os.Args[2] == "orderer" {
			err = watcher.Add("/opt/config/crypto-config/orderers_base64")
			if err != nil {
				log.Fatal(err)
			}
		} else {
			err = watcher.Add("/opt/config/crypto-config/"+ os.Args[2] +"."+ os.Args[1] +"_base64")
			if err != nil {
				log.Fatal(err)
			}
		}
	}
	<-done
}

func refresh() {
    log.Println("args: ", os.Args[:])
    scriptFile := ""
    command := ""
    if os.Args[1] == "bcos" {
    	scriptFile = "refresh_bcos.sh"
		command = "./" + scriptFile + " ./"//脚本的路径
	} else if os.Args[1] == "chainmaker" {
		command = "./refresh_chainmaker.sh " + os.Args[2] + " ./"//脚本的路径
	} else {
		if os.Args[2] == "orderer" {
			scriptFile = "refresh_orderer.sh"
		} else {
			scriptFile = "refresh_peer.sh"
		}
		command = "./" + scriptFile + " " + os.Args[1] + " " + os.Args[2] + " " + os.Args[3] + " ./"//脚本的路径
	}

    cmd := exec.Command("/bin/bash", "-c",command)
    var out bytes.Buffer

    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%s", out.String())
}
